import Excel from 'exceljs'
import path from 'path'
import { isExistFile } from './helper'
/**
 * @typedef {Object} excelOption
 * @property {String} sheetName
 * @property {Object[]} sheetHeader
 * @property {Object[]} sheetData

 * 
 */
/**
 * 导出excel
 * @param {excelOption[]} arr
 * @param {String} filePath
 * @param {String} fileName
 * @returns
 */
export async function exportExcel(arr, filePath, fileName) {
  // sheetName,sheetHeader,sheetData,filePath,fileName
  const workbook = new Excel.Workbook() // 创建工作簿
  arr.some((option) => {
    const sheet = workbook.addWorksheet(option.sheetName) // 创建工作表

    // 添加表头
    // sheet.columns = [
    //   { header: 'Column 1', key: 'col1', width: 30 },
    //   { header: 'Column 2', key: 'col2', width: 30 },
    //   // ... 根据需要添加更多列
    // ];
    // 添加表头
    sheet.columns = option.sheetHeader
    // 获取表头行
    let headerRow = sheet.getRow(1)
    // 表头样式设置
    headerRow.eachCell({ includeEmpty: false }, (cell) => {
      cell.fill = {
        type: 'pattern',
        pattern: 'solid',
        fgColor: { argb: 'FFFF00' } // 黄色背景
      }
      cell.border = {
        top: { style: 'thin' },
        left: { style: 'thin' },
        bottom: { style: 'thin' },
        right: { style: 'thin' }
      }
      cell.font = {
        bold: true
      }
      cell.alignment = {
        horizontal: 'center'
      }
    })
    // 添加数据行
    option.sheetData.forEach((row) => {
      sheet.addRow(row)
    })
    // 数据行添加边框
    let allRows = sheet.getRows(2, option.sheetData.length + 1)
    allRows.forEach((row, index) => {
      row.eachCell({ includeEmpty: false }, (cell, colNum) => {
        // 设置第一列左侧边框
        if (colNum == 1) {
          cell.border = {
            left: { style: 'thin' }
          }
        }
        // 设置最后一列右侧边框
        if (colNum == option.sheetHeader.length) {
          cell.border = {
            right: { style: 'thin' }
          }
        }
        // 设置最后一行底部边框
        if (index == allRows.length - 2) {
          cell.border = {
            ...cell.border,
            bottom: { style: 'thin' }
          }
        }
      })
    })
  })
  let finalPath = ''
  // 文件是否存在
  let isExist = true
  // 后缀叠加数
  let count = 0
  while (isExist) {
    let tempPath = path.resolve(filePath, fileName + `${count || ''}.xlsx`)
    isExist = await isExistFile(tempPath)
    // 存在则叠加数加一
    if (isExist) {
      count++
    } else {
      // 不存在直接赋值最终路径地址
      finalPath = tempPath
    }
  }
  // 将Excel文件保存到磁盘
  return await workbook.xlsx
    .writeFile(finalPath)
    .then(() => 1)
    .catch(() => 0)
}
